// pages/reply/reply.js

import {
  isFullScreen,
  placeholderArr,
  timeSpan
} from '../../utils/util.js';

import {
  CommentModel
} from '../../models/comment.js';

import {
  Lock
} from '../../models/lock.js';

import {
  Token
} from '../../utils/token.js';

const token = new Token();

const lock = new Lock();

const comment = new CommentModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isFullScreen: isFullScreen(),
    openKeyword: true,
    focus: true,
    inputValue: '',
    placeholder: placeholderArr(),
    comments: [],
    replies: [],
    replyData: {},
    activeReply: false,
    pageIndex: 1,
    loadMore: {
      "show": false,
      "type": "loading"
    },
    replyTotal: 0,
    loadingHidden: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      commentId: options.commentId
    })
  },
  _loadData() {
    comment.findCommentDetail(this.data.commentId).then(res => {
      let arr = new Array();
      let item = res.data;
      item.createTime = timeSpan(item.createTime);
      arr.push(item);
      this.setData({
        comments: arr,
        placeholder: "回复 : " + item.nickName
      })
    })
  },

  _loadChildren() {
    let that = this;
    comment.findCommentDetailChildren(that.data.commentId, that.data.pageIndex).then(res => {

      // 关闭评论加载提示
      wx.hideLoading();

      // 关闭底部触底提示
      that._closeLoadMoreTip();

      // 关闭骨架
      that._closeSkeletonView();

      // 添加评论总数量 
      that.setData({
        replyTotal: res.data.total
      })

      // 加载数据
      if (res.data.result.length > 0) {

        res.data.result.forEach(e => {
          e.createTime = timeSpan(e.createTime);
        })

        //数组合并
        that.data.replies.push.apply(that.data.replies, res.data.result);
        that.setData({
          replies: that.data.replies
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    token.verify().then(res => {
      if (res) {
        this._loadData();
        this._loadChildren();
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.replies.length == this.data.replyTotal) {
      // 加载全部
      this._showLoadedAllTip();
    } else {
      this.data.pageIndex++;
      this._showLoadMoreTip();
      this._loadChildren();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  sendComment() {
    let rootComment = this.data.comments[0];

    if (!this.data.inputValue) {
      this._closeKeyword();
      return;
    }

    if (this.data.activeReply) { // 回复状态
      let param = this.data.replyData;
      param.content = this.data.inputValue;
      comment.operate(param, "reply").then(res => {
        this._closeKeyword();

        if (!res.data.result) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        } else {
          setTimeout(() => {
            wx.showLoading({
              title: '评论成功',
            });
            this._reload();
          }, 1000);
        }
      })
    } else {
      let param = {
        "contentId": rootComment.contentId,
        "replyId": rootComment.userId,
        "parentCommentId": rootComment.id
      }
      param.content = this.data.inputValue;
      comment.operate(param).then(res => {
        this._closeKeyword();

        if (!res.data.result) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        } else {
          setTimeout(() => {
            wx.showLoading({
              title: '评论成功',
            });
            this._reload();
          }, 1000);
        }
      })
    }
  },
  onPopup() {
    this._closeKeyword();
  },
  _openKeyword() {
    this.setData({
      openKeyword: true,
      focus: true
    })
  },
  _closeKeyword() {
    let rootComment = this.data.comments[0];
    this.setData({
      openKeyword: false,
      focus: false,
      inputValue: '',
      replyData: {},
      activeReply: false,
      placeholder: "回复 : " + rootComment.nickName
    })
  },
  onReply(e) {

    let dataset = e.currentTarget.dataset;

    let param = {
      "replyId": dataset.userId,
      "parentCommentId": this.data.commentId,
      "contentId": dataset.contentId,
    }

    this.setData({
      replyData: param,
      activeReply: true,
      placeholder: "回复 : " + dataset.nickName
    })

    this._openKeyword();
  },
  onComment() {
    this._openKeyword();
  },
  _showLoadedAllTip() {
    this.setData({
      loadMore: {
        "show": true,
        "type": "end"
      }
    })
  },
  _showLoadMoreTip() {
    this.setData({
      loadMore: {
        "show": true,
        "type": "loading"
      }
    })
  },
  _closeLoadMoreTip() {
    this.setData({
      loadMore: {
        "show": false,
        "type": "loading"
      }
    })
  },
  _closeSkeletonView() {
    this.setData({
      loadingHidden: false
    });
  },
  /**
   * 评论之后页面初始化
   */
  _commented() {
    this._closeLoadMoreTip();
    this.setData({
      replies: [],
      pageIndex: 1
    })
  },
  _reload() {
    this._commented();
    this._loadChildren();
  },
  onDel(e) {

    let that = this;

    let commentId = e.currentTarget.dataset.id;
    let contentId = e.currentTarget.dataset.contentId;
    let index = e.currentTarget.dataset.index;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          comment.delete(contentId, commentId).then(res => {
            if (res.data) {

              that.data.replies.splice(index, 1);
              that.setData({
                replies: that.data.replies,
                replyTotal: that.data.replyTotal - 1
              })

              if (that.data.replyTotal <= 0) {
                wx.navigateBack({
                  delta: 1,
                })
              }

              lock.unlock();
            }
          }).catch(err => {
            lock.unlock();
          });
        } else if (sm.cancel) {
          lock.unlock();
        }
      }
    })
  },
  onRootDel(e) {

    let commentId = e.detail.id;
    let contentId = e.detail.contentId;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          comment.delete(contentId, commentId).then(res => {
            if (res.data) {
              wx.navigateBack({
                delta: 1,
              })
              lock.unlock();
            }
          }).catch(err => {
            lock.unlock();
          });
        } else if (sm.cancel) {
          lock.unlock();
        }
      }
    })
  }
})